// src/stores/aiMessageStore.js
import { defineStore } from 'pinia';
import { send } from '../../api/aiApis'; // 导入 API 方法


export const useAiMessageStore1 = defineStore('aiMessage', {
  state: () => ({
    messages: [] as Array<{
      key: number;
      content: string;
      role: 'user' | 'ai';
    }>,
    isLoading: false,
    error: null,
  }),

  actions: {
    addMessage(message: { key: number; content: string; role: 'user' | 'ai' }) {
      this.messages.push(message);
    },
    
    clearMessages() {
      this.messages = [];
    },
    
    async sendMessageToAI(content: string,userid: string) {
      try {
        // 1. 添加用户消息
        const userKey = Date.now();
        this.addMessage({ key: userKey, content, role: 'user' });
        
        // 2. 准备 AI 消息（初始为空，用于累积流式数据）
        const aiKey = userKey + 1; // 确保 key 唯一
        this.addMessage({ key: aiKey, content: '', role: 'ai' }); // 添加空 AI 消息
        
        this.isLoading = true;
        this.error = null;

        // 3. 处理流式数据的回调函数
        const handleChunk = (chunk: string) => {
          // 找到当前 AI 消息的索引
          const aiMsgIndex = this.messages.findIndex(msg => msg.key === aiKey);
          if (aiMsgIndex !== -1) {
            // 关键：将 chunk 累加到 AI 消息的 content 中（存储到 state）
            console.log(chunk);
            
            this.messages[aiMsgIndex].content += chunk;
          }
        };

        // 4. 调用流式 API（等待流结束）
        await send(content, handleChunk,userid); // 注意添加 await，确保流结束后再执行后续逻辑

      } catch (error) {
        this.error = error.message || '请求失败';
        console.error('AI 消息请求失败:', error);
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
  },

  getters: {
    getMessages: (state) => state.messages,
    getUserMessages: (state) => state.messages.filter(msg => msg.role === 'user'),
    getAiMessages: (state) => state.messages.filter(msg => msg.role === 'ai'),
  }
});